<template>
  <a-upload
    :disabled="disabled"
    list-type="picture-card"
    :file-list="lList"
    @preview="handlePreview"
    @change="handleChange"
  >
  </a-upload>
</template>
<script>
import Vue from 'vue'

export default {
  name: 'BFilePreview',
  components: {},
  props: {
    list: {
      type: Array,
      default: []
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {}
  },
  computed: {
    lList() {
      if (this.list && this.list.length > 0) {
        let temp = this.$clone(this.list)
        temp.map(v => {
          v.name = v.fileName + v.suffixName
          v.url =
            '/api/ycloud-file-center/oper/download?access_token=' +
            Vue.getAcloudProvider().getAccessToken() +
            '&fileId=' +
            v.fileId
          v.uid = v.id
        })
        return temp
      } else {
        return []
      }
    }
  },
  watch: {},
  created() {
  },
  methods: {
    handleChange({ fileList }) {
      this.$submitConfirm(() => {
        this.$emit('update:list', fileList)
      }, '确认删除？')
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
      })
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      let previewImage = file.url || file.preview
      let modal
      let close = () => {
        modal.destroy()
      }
      modal = this.$info({
        content: () => {
          return <div>
            <a-icon type="close" class="close" onClick={close} />
            <img alt="example" style="width: 100%" src={previewImage} />
          </div>
        },
        class: 'file-preview-modal',
        maskClosable: true
      })
    }
  }
}
</script>